//
//  FollowerViewController.m
//  hospitalVIP
//
//  Created by Xiaoyan on 13-4-7.
//  Copyright (c) 2013年 MEETStudio. All rights reserved.
//

#import "FollowerViewController.h"

#import "FriendInviteCellView.h"

static ASIHTTPConnection *getFollows_connect;
static ASIHTTPConnection *search_user_connect;
static ASIHTTPConnection *userRelation_connect;

@interface FollowerViewController (){
    int pageNo ;
    int userID;
    int followType;
    
    NSMutableArray *searchUserArray;
    NSMutableDictionary *searchStatusDict;
}

@end

@implementation FollowerViewController

@synthesize followersArray;
@synthesize myTableView;
- (void)dealloc{
    
    [searchUserArray release];
    
    [myTableView release];
    if (getFollows_connect != nil) {
        getFollows_connect.connectionDelegate = nil;
        [getFollows_connect release];
        getFollows_connect = nil;
    }
    
    
    if (userRelation_connect != nil) {
        userRelation_connect.connectionDelegate = nil;
        [userRelation_connect release];
        userRelation_connect = nil;
    }
        
    
    if (search_user_connect != nil) {
        search_user_connect.connectionDelegate = nil;
        [search_user_connect release];
        search_user_connect = nil;
    }
    
    [mySearchBar release];
    
    [followersArray release];
    
    [searchStatusDict release];
    
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithUserID:(int)userId followType:(int)type{
    
    self = [super init];
    if (self) {
        userID = userId;
        followType = type;
        
    }
    return self;
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    followersArray = [[NSMutableArray alloc]init];
    
    pageNo = 1;
    
    if (searchStatusDict == nil) {
        searchStatusDict = [[NSMutableDictionary alloc]init];
    }
    
    [self refreshView];
    
    [self loadData];
}

- (void)loadData{
    
    
        
        NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
      //  NSString *UserID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
        
        
        NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/GetMyFollowedFans.aspx?UserID=%d&pageNo=%d",BASEURL,userName,userID,pageNo];
        NSURL *url = [NSURL URLWithString:urlString];
        
        
        if (followType == 1) {
            urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/GetMyFollowedUsers.aspx?UserID=%d&pageNo=%d",BASEURL,userName,userID,pageNo];
            url = [NSURL URLWithString:urlString];
            
          
            
        }
        
        if (getFollows_connect != nil) {
            getFollows_connect.connectionDelegate = nil;
            [getFollows_connect release];
            getFollows_connect = nil;
        }
        
        getFollows_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
        getFollows_connect.connectionDelegate = self;
        
        [getFollows_connect startAsynchronous];
        
        [LoadingView showDefaultLoadingView];
        
    
    
}


- (void)checkRelation:(id)sender
{
    
    int selfUid = [[[NSUserDefaults standardUserDefaults]valueForKey:USER_ID] intValue];
    
    UIButton *button = (UIButton *)sender;
    
    int friendId = [[searchUserArray objectAtIndex:button.tag] objectForKey:USER_ID];
    
    
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CheckFollowRelationship.aspx?UserID=%d&FriendID=%d",BASEURL,userName,selfUid,friendId];
    NSURL *url = [NSURL URLWithString:urlString];
    
    if (userRelation_connect != nil) {
        
        userRelation_connect.connectionDelegate = nil;
        [userRelation_connect release];
        userRelation_connect = nil;
    }
    
    
    userRelation_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:NO];
    userRelation_connect.connectionDelegate = self;
    
    [userRelation_connect startAsynchronous];
    
    
}


#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	/*
	 Update the filtered array based on the search text and scope.
	 */
    
    CLog(@"scope %@", scope);
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/SearchUsers.aspx?keyword=%@",BASEURL, userName, searchText];
    
    NSString *encodedValue = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
	NSURL *url = [NSURL URLWithString:encodedValue];
    
    if (search_user_connect != nil) {
        search_user_connect.connectionDelegate = nil;
        [search_user_connect release];
    }
    
    search_user_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:NO];
    search_user_connect.connectionDelegate = self;
    [search_user_connect startAsynchronous];
    
    CLog(@"search baby  request %@", url);
    
}




- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:YES];
    
    CLog(@" dict %@",dict);
    
    NSString *urlStr = [url absoluteString];
    NSRange range = [urlStr rangeOfString:@"GetMyFollowedUsers"];
    
    if (range.length > 0) {
        if (dict) {
            NSArray *array = [dict objectForKey:@"Records"];
                            
                if (pageNo == 1) {
                    [followersArray removeAllObjects];
                }
                
                [followersArray addObjectsFromArray:array];
                [myTableView reloadData];
                [self refreshView];
           
        }
        return;
        
    }
    
    
    //搜索
     range = [urlStr rangeOfString:@"SearchUsers.aspx"];
    if (range.length > 0) {
        
        if (searchUserArray == nil) {
            searchUserArray = [[NSMutableArray alloc]init];
        }
        else{
            
            [searchUserArray removeAllObjects];
        }
        
        
               
        NSArray *array = [[dict objectForKey:@"results"] objectForKey:@"Records"];
        
        if ([array count] >0) {
            
            [searchUserArray addObjectsFromArray:array];
            
           
//            for (NSDictionary *searchBabyDict in array) {
//                [searchStatusDict setValue:[searchBabyDict objectForKey:@"attentionStatus"] forKey:[searchBabyDict objectForKey:@"UserID"]];
//            }
            
            [self.searchDisplayController.searchResultsTableView reloadData];
        }
        return;
    }

    
    
    range = [urlStr rangeOfString:@"GetMyFollowedFans"];
    if (range.length > 0) {
        if (dict) {
            NSArray *array = [dict objectForKey:@"Records"];
            
            if (pageNo == 1) {
                [followersArray removeAllObjects];
            }
            
            [followersArray addObjectsFromArray:array];
            [myTableView reloadData];
            [self refreshView];
            
        }
        return;
        
    }
    
    
    range = [urlStr rangeOfString:@"FollowUserInDomain"];
    if (range.length > 0) {
        
        if (dict != nil && ![[dict objectForKey:@"isSuccess"] boolValue]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[dict objectForKey:@"messageContent"]
                                                           delegate:self
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            
        }
        
        [self headerRefData];
        return;
    }
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [LoadingView hideWithAnimated:NO];
}

#pragma mark tableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return searchUserArray.count;
    }
    
    if (followersArray.count == 0) {
        return 1;
    }
    
    return followersArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        
        NSDictionary *dict = [searchUserArray objectAtIndex:indexPath.row];
        
        static NSString *MyIdentifier = @"FriendInviteCellView";
        // Try to retrieve from the table view a now-unused cell with the given identifier.
        FriendInviteCellView *cell =(FriendInviteCellView *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FriendInviteCellView"
                                                         owner:self options:nil];
#ifdef __IPHONE_2_1
            cell = (FriendInviteCellView *)[nib objectAtIndex:0];
#else
            cell = (FriendInviteCellView *)[nib objectAtIndex:1];
#endif
            
            
            
            [cell.titleLabel setFrame:CGRectMake(60, 5, 100, 24)];
            [cell.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [cell.titleLabel setTextColor:[UIColor colorWithRed:55.0/255 green:87.0/255 blue:122.0/255 alpha:1.0]];
            
            
            UILabel *roleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 26, 100, 12)];
            roleLabel.backgroundColor = [UIColor clearColor];
            roleLabel.tag = 111;
            [roleLabel setFont:[UIFont systemFontOfSize:10]];
            [roleLabel setTextColor:[UIColor colorWithRed:55.0/255 green:87.0/255 blue:122.0/255 alpha:1.0]];
            roleLabel.text = [dict objectForKey:@"birthdate"];
            [cell.contentView addSubview:roleLabel];
            [roleLabel release];

            
            
            UIButton *button = cell.actionButton;
            [button setFrame:CGRectMake(250, 10, 60, 34)];
            
            [button addTarget:self action:@selector(checkRelation:) forControlEvents:UIControlEventTouchUpInside];
            //[button setImage:[UIImage imageNamed:@"button_addAttention.png"] forState:UIControlStateNormal];
            button.tag = indexPath.row;
            
            UILabel *addLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -4, CGRectGetWidth(button.frame), CGRectGetHeight(button.frame))];
            [addLabel setFont:[UIFont systemFontOfSize:10]];
            
            [addLabel setTextAlignment:UITextAlignmentCenter];
           // addLabel.text = @"关注";
                      
//            NSString *statuscode = [searchStatusDict objectForKey:[dict objectForKey:@"id"]];
//            if ([statuscode isEqualToString:@"await"]) {
//                
//                [addLabel setText:@"等待同意"];
//            }
//            else{
//                [addLabel setText:@"加关心"];
//                
//            }
            
            addLabel.tag = 110;
            [addLabel setBackgroundColor:[UIColor clearColor]];
            [button addSubview:addLabel];
            
        }
        
        for (UIView *subView in [cell subviews]) {
            subView.tag = indexPath.row;
        }
        
        
        UILabel *roleLable = (UILabel *)[cell viewWithTag:111];
        if (![[dict objectForKey:@"RankType"] isMemberOfClass:[NSNull class]]) {
            
            int RankType = [[dict objectForKey:@"RankType"] intValue];
            if (RankType == 1) {
                roleLable.text = @"普通用户";
            }
            if (RankType == 2) {
                roleLable.text = @"社区医生";
            }
            if (RankType == 3) {
                roleLable.text = @"中心医院医生";
            }
            
        }
        
        
        cell.titleLabel.text = [dict objectForKey:@"DisplayName"];
        [cell.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
        
        //ICON
//        if(![[dict objectForKey:@"attachmentId"] isMemberOfClass:[NSNull class]]){
//            
//            NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",BASEURL,@"/commons/attachment/download",[dict objectForKey:@"attachmentId"]];
//            NSURL *url = [NSURL URLWithString:string];
//            [cell.imageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon];
//        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setSelected:NO];
        
        cell.tag = indexPath.row;
        [cell.actionButton setImage:[UIImage imageNamed:@"button_addAttention.png"] forState:UIControlStateNormal];
        
        [cell.imageAction setTag:indexPath.row];
        [cell.imageAction addTarget:self action:@selector(toUserView:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
  
    else{
    
    
    static NSString *MyIdentifier = @"TimelineUnitCell";
    
    // Try to retrieve from the table view a now-unused cell with the given identifier.
    LPFriendCell *cell =(LPFriendCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LPFriendCell"
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
        cell = (LPFriendCell *)[nib objectAtIndex:0];
#else
        cell = (LPFriendCell *)[nib objectAtIndex:1];
#endif
        
       
        
        
    }
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *dict;
    if (followersArray.count > 0) {
        
        dict = [followersArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = [dict objectForKey:@"displayName"];
        
        if (followType == 1) {
            [cell.invitationBtn setTitle:@"取消关注" forState:UIControlStateNormal];
        }
        else{
            [cell.invitationBtn setTitle:@"关注" forState:UIControlStateNormal];
        }
        
        cell.invitationBtn.tag = [[dict objectForKey:@"userId"] intValue];
        [cell.invitationBtn addTarget:self action:@selector(followUserAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    else{
        cell.invitationBtn.hidden = YES;
        cell.headerView.hidden = YES;
    }
    
    
    return cell;
        
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        NSDictionary *dict = [searchUserArray objectAtIndex:indexPath.row];
        PersonalViewController * detailViewController =   [[PersonalViewController alloc] initWithUserDict:dict];
        
        detailViewController.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
        
    }
    else{
        
        if (followersArray.count == 0) {
            return;
        }
        
        NSDictionary *dict = [followersArray objectAtIndex:indexPath.row];
        PersonalViewController * detailViewController =   [[PersonalViewController alloc] initWithUserDict:dict];
        
        detailViewController.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];

        
        
    }
    
        
}


- (void)toUserView:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    
    NSDictionary *dict = [searchUserArray objectAtIndex:button.tag];
    PersonalViewController * detailViewController =   [[PersonalViewController alloc] initWithUserDict:dict];
    
    detailViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];

    
    
}


#pragma mark - UISearchBarDelegate
//实现现场搜索：即用户键入时可看见搜索结果的改变
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"])
    {
        [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:nil];
        
    }
    else
    {
        return;
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"])
    {
        
        return YES;
    }
    else
    {
        return NO;
    }
    
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    self.navigationController.navigationBar.hidden = YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
{
    
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:nil];
    CLog(@"searchBarSearchButtonClicked");
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar;
{
    [self.navigationController setNavigationBarHidden:NO];
    [self loadData];
    
}


#pragma mark - UISearchDisplayDelegate

// when we start/end showing the search UI
- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    
}
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
    
}
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    
}
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    
}

#pragma mark 取消关注
- (void)followUserAction:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    int friendID = button.tag;
    
    int isDeleteFollow = 0;
    if (followType == 1) {
        isDeleteFollow = 1;
        
    }
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/FollowUserInDomain?UserID=%d&FriendID=%d&isDeleteFollow=%d",BASEURL,userName,userID,friendID,isDeleteFollow];
    NSURL *url = [NSURL URLWithString:urlString];
    
    if (getFollows_connect != nil) {
        getFollows_connect.connectionDelegate = nil;
        [getFollows_connect release];
        getFollows_connect = nil;
    }
    
    getFollows_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:NO];
    getFollows_connect.connectionDelegate = self;
    
    [getFollows_connect startAsynchronous];
    
    [LoadingView showDefaultLoadingView];

    
    
}


#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods


- (void)refreshView
{
    
    //顶部刷新条
    if ( _refreshHeaderView == nil) {
        
        _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f- self.myTableView.bounds.size.height, 320, self.myTableView.bounds.size.height)];
        _refreshHeaderView.delegate = self;
        [self.myTableView addSubview:_refreshHeaderView];
    }
    
    
    //底部刷新条
    if ( _refreshTailView == nil) {
        
        _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, self.myTableView.frame.size.height)];
        _refreshTailView.delegate = self;
        [self.myTableView addSubview:_refreshTailView];
        
    }
    
    if (_refreshTailView != nil) {
        float height = MAX(self.myTableView.contentSize.height, self.myTableView.frame.size.height);
        [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, self.myTableView.frame.size.height)];
    }
    
    
}



//顶部刷新事件
- (void)headerRefData
{
    _HeaderReloading = YES;
    pageNo = 1;
    [self loadData];
    
}

- (void)headerRefDone
{
    _HeaderReloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
}

//底部刷新事件
- (void)bottomRefData
{
    
    
    _TailReloading = YES;
    
    pageNo ++;
    
    if (followersArray.count == 0) {
        pageNo = 1;
    }
    
    [self loadData];
    
}

- (void)bottomRefDone
{
    _TailReloading = NO;
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
    }
    
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}


#pragma mark -
#pragma mark EGORefreshTableTailDelegate Methods

- (void)egoRefreshTableTailDidTriggerRefresh:(EGORefreshTableTailView*)view{
	
	[self bottomRefData];
    
}

- (BOOL)egoRefreshTableTailDataSourceIsLoading:(EGORefreshTableTailView*)view{
	
    
    return _TailReloading;
	
}

- (NSDate*)egoRefreshTableTailDataSourceLastUpdated:(EGORefreshTableTailView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    
	[self headerRefData];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
	
	//return _reloading; // should return if data source model is reloading
    return _HeaderReloading;
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
